import React from 'react';
import './index.css';

import mzsdk from '../../../../utils/mzsdk';

import { Toast } from 'antd-mobile';

/**
 * 投票组件
 */

export default class Vote extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            voteInfo: null,//投票信息
            options: null,//投票所有选项

            selectedOptionIds: [],//选中的选项ID
        }
    }

    componentDidMount() {
        this.getVoteInfo()
    }

    getVoteInfo = () => {
        if (!this.props.ticketInfo) {
            Toast.info('活动信息是空的', 1.5)
            return;
        }
        var _this = this;
        mzsdk.vote.getVoteInfo({ channelId: this.props.ticketInfo.channel_id, ticketId: this.props.ticketInfo.ticket_id }).then(res => {
            console.log('获取的投票信息：', res)
            _this.setState({
                voteInfo: res
            }, () => {
                _this.getVoteOptions()
            })
        }, (err) => {
            Toast.info(err.msg, 1.5)
        })
    }

    getVoteOptions = () => {
        var _this = this;
        mzsdk.vote.getVoteOptions({ voteId: this.state.voteInfo.id }).then(res => {
            console.log('获取投票的所有选项：', res)
            _this.setState({
                options: res
            })
        }, (err) => {
            Toast.info(err.msg, 1.5)
        })
    }

    votePost = () => {
        let { selectedOptionIds } = this.state;
        if (selectedOptionIds.length <= 0) {
            return;
        }
        const ids = selectedOptionIds.join(',')
        console.log('该投票选择的选项ID为：', ids)
        var _this = this;
        mzsdk.vote.votePost({ ticketId: this.props.ticketInfo.ticket_id, voteId: this.state.voteInfo.id, optionId: ids }).then(res => {
            _this.getVoteInfo()
        }, (err) => {
            Toast.info(err.msg, 1.5)
        })
    }

    toDate = (second) => {
        if (!second) return '';
        var date = new Date((second * 1000))
        var year = date.getFullYear();  //取得4位数的年份
        var month = date.getMonth() + 1;  //取得日期中的月份，其中0表示1月，11表示12月
        month = month < 10 ? '0' + month : month
        var day = date.getDate();      //返回日期月份中的天数（1到31）
        day = day < 10 ? '0' + day : day
        var hour = date.getHours();     //返回日期中的小时数（0到23）
        hour = hour < 10 ? '0' + hour : hour
        var minute = date.getMinutes(); //返回日期中的分钟数（0到59）
        minute = minute < 10 ? '0' + minute : minute
        var second = date.getSeconds(); //返回日期中的秒数（0到59）
        second = second < 10 ? '0' + second : second
        var res = year + "-" + month + "-" + day + " " + hour + ":" + minute;
        return res;
    }

    clickOption = (option) => {
        let { selectedOptionIds, voteInfo } = this.state;
        if (voteInfo.is_deleted == '1') return;// 已删除不响应
        if (voteInfo.is_vote == '1') return;// 已投不响应
        if (voteInfo.is_expired == '1') return;// 过期不响应

        let index = selectedOptionIds.findIndex(t => t === option.id)

        if (voteInfo.select_type == '0') {//单选
            if (index > -1) {
                selectedOptionIds = []
            } else {
                selectedOptionIds = []
                selectedOptionIds.push(option.id)
            }
        } else {//多选
            if (index > -1) {
                selectedOptionIds.splice(index, 1)
            } else {
                if (selectedOptionIds.length >= voteInfo.max_select) {
                    let error = '最多选择' + voteInfo.max_select + '项'
                    Toast.info(error, 1.5)
                    return;
                } else {
                    selectedOptionIds.push(option.id)
                }
            }
        }

        this.setState({
            selectedOptionIds: selectedOptionIds
        })
    }

    render() {
        let { voteInfo, options, selectedOptionIds } = this.state;
        /**
         * voteInfo
         * type: '0'是文字投票 ‘1’是图文投票
         * select_type: '0'是单选 ‘1’是多选
         * max_select: 最多选择项限制
         * status: ’0’该投票活动下线了 ‘1’该投票活动上线中
         * is_deleted: '0'该投票活动未删除 ‘1’该投票活动已删除
         * is_vote: '0'未投票 ‘1’已经投过票
         * is_expired: ‘0’未过期 ‘1’已过期
         */
        return (
            <div className="mz-vote-background">
                {
                    this.props.ticketInfo && voteInfo ? <div className="mz-vote-content">
                        <div className="mz-vote-name">{voteInfo.question}</div>
                        <div className="mz-vote-intro">
                            <div className="mz-vote-select-type">{voteInfo.select_type == '1' ? '多选(' + '最多选择' + voteInfo.max_select + '项)' : '单选'}</div>
                            <div className="mz-vote-expired-time">结束时间：{this.toDate(voteInfo.end_time)}</div>
                        </div>
                        {
                            voteInfo.type == '1' ? <div className="vote-image-background">
                                {/* 图文投票 */}
                                {
                                    options && options.length > 0 && options.map((item, index) => {
                                        return (
                                            <div key={index} className="vote-image-item">
                                                {
                                                    (voteInfo.is_vote == '1' || voteInfo.is_expired == '1') ?
                                                        <div className={item.is_vote ? 'percent-count' : 'percent-count other'}>{item.vote_num}票</div> :
                                                        <div className={selectedOptionIds.findIndex(t => t === item.id) > -1 ? 'image-vote-select image-vote-s-button' : 'image-no-vote-select image-vote-s-button'} onClick={this.clickOption.bind(this, item)}></div>
                                                }
                                                <div className="vote-image-title-background">
                                                    <div className="vote-image-title">{item.title}</div>
                                                </div>
                                                <img className="vote-image" src={item.image}></img>
                                            </div>
                                        )
                                    })
                                }
                            </div> : <div className="vote-text-background">
                                {/* 文字投票 */}
                                {
                                    options && options.length > 0 && options.map((item, index) => {
                                        return (
                                            <div key={index} className="vote-text-item" style={{ background: item.is_vote ? 'rgba(255,91,41,0.06' : '#fbfbfb' }}>
                                                {
                                                    (voteInfo.is_vote == '1' || voteInfo.is_expired == '1') &&
                                                    <div>
                                                        {
                                                            item.vote_num > 0 && <div className={item.is_vote ? 'percent-bg' : 'percent-bg other'} style={{ width: (item.percentage + '%') }}></div>
                                                        }
                                                    </div>

                                                }
                                                <div className="vote-text">{item.title}</div>
                                                {
                                                    voteInfo.is_vote == '1' || voteInfo.is_expired == '1' ?
                                                        <div className="vote-count" style={{ color: item.is_vote > 0 ? '#ff5b29' : '#6f6f6f' }}>{item.percentage}% </div> :
                                                        <div className={selectedOptionIds.findIndex(t => t === item.id) > -1 ? 'text-vote-select text-vote-s-button' : 'text-no-vote-select text-vote-s-button'} onClick={this.clickOption.bind(this, item)}></div>
                                                }
                                            </div>
                                        )
                                    })
                                }
                            </div>
                        }
                        {
                            voteInfo.is_vote == '1' || voteInfo.is_expired == '1' ? <div></div> :
                                <div className="vote-control">
                                    <div className="vote-note">投票后可查看结果</div>
                                    <div className="vote-to-vote" onClick={this.votePost}>投票</div>
                                </div>
                        }
                    </div> :
                        <div className="mz-vote-empty">暂无投票活动</div>
                }
            </div>
        )
    }
}
